﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using La.Code.Log;
using La.Code.SocketUtil;
using La.Code.Xml;
//using La.Code.Excel;

namespace LiAnProxy
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }
        private void Main_Load(object sender, EventArgs e)
        {

            DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn
            {
                Name = "ProxyName",
                DataPropertyName = "ProxyName",
                HeaderText = @"业务名字",
                DisplayIndex = 0
            };

            DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn
            {
                Name = "ProxyIp",
                DataPropertyName = "ProxyIp",
                HeaderText = @"代理IP",
                DisplayIndex = 2
            };

            DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ProxyPort",
                Name = "ProxyPort",
                HeaderText = @"代理端口",
                DisplayIndex = 2
            };

            DataGridViewTextBoxColumn col3 = new DataGridViewTextBoxColumn();
            col3.DataPropertyName = "TargetIp";
            col3.Name = "TargetIp";
            col3.HeaderText = @"目标IP";
            col3.DisplayIndex = 3;

            DataGridViewTextBoxColumn col4 = new DataGridViewTextBoxColumn
            {
                DataPropertyName = "TargetPort",
                Name = "TargetPort",
                HeaderText = @"目标端口",
                DisplayIndex = 4
            };

            DataGridViewTextBoxColumn col5 = new DataGridViewTextBoxColumn
            {
                DataPropertyName = "TargetTimeOut",
                Name = "TargetTimeOut",
                HeaderText = @"超时时间",
                DisplayIndex = 5
            };

            DataGridViewTextBoxColumn col6 = new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ProxyMax",
                Name = "ProxyMax",
                HeaderText = @"最大处理",
                DisplayIndex = 6
            };

            DataGridViewTextBoxColumn col7 = new DataGridViewTextBoxColumn
            {
                DataPropertyName = "ProxyType",
                Name = "ProxyType",
                HeaderText = @"代理类型",
                DisplayIndex = 1
            };
            //col7.Visible = false;
            // col7.DisplayIndex = 0;

            DataGridViewButtonColumn btn = new DataGridViewButtonColumn
            {
                Name = "DeleteBtn",
                HeaderText = @"操作",
                Text = "",
                DisplayIndex = 8,
                DefaultCellStyle = { NullValue = "删除" }
            };
            dataGridView1.Columns.Add(col);
            dataGridView1.Columns.Add(col1);
            dataGridView1.Columns.Add(col2);
            dataGridView1.Columns.Add(col3);
            dataGridView1.Columns.Add(col4);
            dataGridView1.Columns.Add(col5);
            dataGridView1.Columns.Add(col6);
            dataGridView1.Columns.Add(col7);
            dataGridView1.Columns.Add(btn);
            //关闭自动顺序
            dataGridView1.AutoGenerateColumns = false;
        }

        /// <summary>
        /// 委托 消息
        /// </summary>
        /// <param name="str">类容</param>
        /// <param name="type">类型 1、消息，2、添加到卡集合,3、添加到内容集合</param> 
        public delegate void ShowMesDelegate(string str, int type);
        /// <summary>
        /// 委托 消息
        /// </summary>
        /// <param name="str">类容</param>
        /// <param name="type">类型 1、消息，2、添加到卡集合,3、添加到内容集合</param>
        public void ShowMes(string str, int type)
        {
            try
            {
                switch (type)
                {
                    case 1:
                        if (MesLbl.InvokeRequired)
                            Invoke(new ShowMesDelegate(ShowMes), str, type);
                        else
                            MesLbl.Text = str;
                        break;
                }
            }
            catch (Exception ex)
            {
                //  String dd = ex.Message;
            }
        }




        /// <summary>
        /// Socket提交缴费
        /// </summary>
        /// <param name="sendStr"></param>
        /// <param name="length"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public byte[] ByteData(byte[] sendStr, int length, string url)
        {
            try
            {
                // Model.Pay_Business Config = ConfigHelper.GetConfig(serviceName.Trim()); //得到配置文件 
                string Url = url;
                string[] urlTemp = Url.Split(':');
                byte[] data = new byte[length];

                IPAddress hostIp = IPAddress.Parse(urlTemp[0]);
                IPEndPoint point = new IPEndPoint(hostIp, Int32.Parse(urlTemp[1]));
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(point);
                socket.Send(sendStr, sendStr.Length, 0);
                IPEndPoint senderIp = new IPEndPoint(IPAddress.Any, 0);
                EndPoint remote = senderIp;
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 60000);
                int recv = socket.ReceiveFrom(data, ref remote);
                if (recv > 0)
                {
                }
                socket.Close();
                return data;
            }
            catch (Exception ex)
            {
                //Helper.WriteLog.WriteError("[服务连接错误][" + serviceName + "]", "错误日志", ex);
                ShowMes("[服务连接错误][" + url + "]" + ex.Message, 1);
                //throw;
                return null;

            }
        }
        private void TcpTestBtn_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            { 
                try
                {
                    byte[] sendStr = System.Text.Encoding.Default.GetBytes(" 01;09;liankeji;0;03719208;|");
                    byte[] data = ByteData(sendStr, 1024, "127.0.0.1:" + txtPort.Text);
                    Encoding encoding = Encoding.GetEncoding("utf-8");

                    this.Invoke(new Action(() =>
                    {
                        ShowMes(DateTime.Now + ",服务端:" + encoding.GetString(data, 0, data.Length), 1);
                    }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, @"错误");
                }
            });

        }


        private void button2_Click(object sender, EventArgs e)
        {
            string dd = System.AppDomain.CurrentDomain.BaseDirectory;
            proxy_ShowMesEvent("dd", 1);
            ;
        }

        void proxy_ShowMesEvent(string str, int type)
        {

            string dd = DateTime.Now.ToString(CultureInfo.InvariantCulture) + ",服务端:" + str;
            var log = LogFactoryWindows.GetLogger(GetType());
            log.Info(str);
        }


        void _server_WriteErrorLogEvent(IDataTransmit sender, string content, Exception ex)
        {
            //var log = LogFactoryWindows.GetLogger(GetType());
            //log.Error(ex);
            ShowMes(ex.Message + " " + ex.StackTrace, 1);
        }



        /// <summary>
        /// Scket 监听集合
        /// </summary>
        private readonly List<ProxySocket> _proxySocketModelS = new List<ProxySocket>();
        private readonly List<ProxyHttp> _proxyHttpModelS = new List<ProxyHttp>();

        /// <summary>
        /// 打开添加 socket代理界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void socketToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddSocket temp = new AddSocket
            {
                ReturnDelegate = Showvalue
            };
            temp.Show();
        }
        /// <summary>
        /// 接受 socket代理界面 返回的值
        /// </summary>
        /// <param name="socketModel"></param>
        private void Showvalue(ProxyModel socketModel)
        {
            try
            {
                AddSocketProxy(socketModel);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"错误");
            }
            ShowProxy();

        }

        void ShowProxy()
        {
            //更新列表
            List<ProxyModel> modelS = _proxySocketModelS.Select(item => item.SocketModel).ToList();
            modelS.AddRange(_proxyHttpModelS.Select(item => item.SocketModel));
            dataGridView1.DataSource = modelS;
            //写入配置文件
            bool tem = XmlSerializerHelper.XmlWriteFilePath(@"SocketProxyConfig.ini", modelS);
            if (tem)
            {
            }
            else
            {
                MessageBox.Show(@"写入配置文件失败", @"失败");
            }

        }
        /// <summary>
        /// 添加socket 代理
        /// </summary>
        /// <param name="socketModel"></param>
        private void AddSocketProxy(ProxyModel socketModel)
        {
            if (socketModel.ProxyType == ProxyType.Socket)
            {

                ProxySocket proxySocket = new ProxySocket(socketModel.ProxyName, socketModel.ProxyPort, socketModel.ProxyMax, socketModel.TargetIp, socketModel.TargetPort, socketModel.TargetTimeOut);
                proxySocket.ShowMesEvent += proxy_ShowMesEvent;
                proxySocket.WriteErrorLogEvent += _server_WriteErrorLogEvent;
                proxySocket.Start();
                _proxySocketModelS.Add(proxySocket);
            }
            else
            {
                ProxyHttp proxySocket = new ProxyHttp(socketModel.ProxyPort, socketModel.ProxyMax, socketModel.TargetIp, socketModel.TargetPort, socketModel.TargetTimeOut);
                proxySocket.ShowMesEvent += proxy_ShowMesEvent;
                proxySocket.WriteErrorLogEvent += _server_WriteErrorLogEvent;
                proxySocket.Start();
                _proxyHttpModelS.Add(proxySocket);
            }
        }




        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int rowindex = e.RowIndex;
                if (rowindex >= 0)
                {
                    DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                    if (column is DataGridViewButtonColumn)
                    {
                        string proxyIp = dataGridView1.Rows[rowindex].Cells["ProxyIp"].Value.ToString(); //代理地址
                        string proxyPort = dataGridView1.Rows[rowindex].Cells["ProxyPort"].Value.ToString(); //代理IP
                        // MessageBox.Show("ProxyIp:" + ProxyIp + ",ProxyPort:" + ProxyPort);
                        foreach (var item in _proxySocketModelS)
                        {
                            if (item.SocketModel.ProxyIp.Equals(proxyIp))
                            {
                                if (item.SocketModel.ProxyPort == Convert.ToInt32(proxyPort))
                                {
                                    item.Stop();
                                    _proxySocketModelS.Remove(item);
                                    break;

                                }
                            }

                        }
                        ShowProxy();
                    }
                }
                else
                {
                    //MessageBox.Show("没有");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, @"错误");
            }

        }

        private void 本地记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<ProxyModel> modelS = XmlSerializerHelper.XmlReadFilePath<List<ProxyModel>>(@"SocketProxyConfig.ini");
            if (modelS != null)
            {
                foreach (var item in modelS)
                {
                    try
                    {
                        AddSocketProxy(item);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, @"错误");
                    }
                }
                ShowProxy();
            }
        }

        private void httpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddHttpProxy temp = new AddHttpProxy
            {
                ReturnDelegate = Showvalue
            };
            temp.Show();
        }

    }

}
